<?php
namespace adapter;

class PDO implements DatabaseInterface
{
    protected $conn;
    
    public function connect($host, $port, $dbName, $user, $pwd)
    {
        try {
            $port = $port ?? '3306';
            $conn = new \PDO("mysql:host=$host:$port;dbname=$dbName", $user, $pwd);
            $conn->query("set names utf8");
            $this->conn = $conn;
        } catch(\Exception $e) {
            echo '数据库连接失败: ' . $e->getCode() . $e->getMessage();
            return false;
        }        
        $this->conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); //属性名 属性值 数组以关联数组返回
    }

    public function query($sql)
    {
        $res = $this->conn->query($sql);
        return $res->fetchAll();
    }

    public function close()
    {
        unset($this->conn);
    }

}



